<template>
  <div>
    <!-- 面包写导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-alert show-icon title="注意：只允许为三级分类设置相关参数！" :closable="false" type="warning"></el-alert>
      <el-row>
        <el-col>
          <p>
            选择商品分类：
            <el-cascader v-model="selectedKeys" :options="cateList" :props="cateListProp" @change="handleChange"></el-cascader>
          </p>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-row>
            <el-col>
              <el-button :disabled="btnLocked" @click="showAddDialog" type="primary" size="mini">添加参数</el-button>
            </el-col>
          </el-row>
          <el-table :data="manyList" border stripe>
            <el-table-column type="expand">
              <template v-slot="scoped">
                <el-tag v-for="(item, i) in scoped.row.attr_vals" closable :key="i" @close="handleClose(i, scoped.row)">{{
                  item
                }}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scoped.row.inputVisible"
                  v-model="scoped.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scoped.row)"
                  @blur="handleInputConfirm(scoped.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scoped.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"> </el-table-column>
            <el-table-column label="操作">
              <template v-slot="scoped">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scoped.row.attr_id)"
                  >编辑</el-button
                >
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteCate(scoped.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-row>
            <el-col>
              <el-button :disabled="btnLocked" type="primary" size="mini" @click="showAddDialog">添加属性</el-button>
            </el-col>
          </el-row>
          <el-table :data="onlyList" border stripe>
             <el-table-column type="expand">
              <template v-slot="scoped">
                <el-tag v-for="(item, i) in scoped.row.attr_vals" closable :key="i" @close="handleClose(i, scoped.row)">{{
                  item
                }}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scoped.row.inputVisible"
                  v-model="scoped.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scoped.row)"
                  @blur="handleInputConfirm(scoped.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scoped.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"> </el-table-column>
            <el-table-column label="操作">
              <template v-slot="scoped">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scoped.row.attr_id)"
                  >编辑</el-button
                >
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteCate(scoped.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加模态框 -->
    <el-dialog :title="'添加' + textTitle" :visible.sync="addDialogVisible" width="50%" @close="addFormClose">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="textTitle" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addFormPost">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑模态框 -->
    <el-dialog :title="'编辑' + textTitle" :visible.sync="editDialogVisible" width="50%" @close="editFormClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="textTitle" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editFormPost">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur'
          }
        ]
      },
      editForm: {
        attr_name: ''
      },
      editFormRules: {
        attr_name: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur'
          }
        ]
      },
      cateList: [],
      cateListProp: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      selectedKeys: [],
      activeName: 'many',
      manyList: [],
      onlyList: [],
      addDialogVisible: false,
      editDialogVisible: false
    }
  },
  methods: {
    async getCateData() {
      const { data: res } = await this.$http.get('categories')
      console.log(res)
      this.cateList = res.data
    },
    handleChange() {
      this.getTabData()
    },
    async getTabData() {
      if (this.selectedKeys.length !== 3) {
         this.selectedKeys = []
         this.manyList = []
         this.onlyList = []
         return 
      }
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: this.activeName
        }
      })
      if (res.meta.status !== 200) return this.$message.error('获取参数失败')
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals.length ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      console.log(res.data)
      //   console.log(res.data)
      if (this.activeName === 'many') {
        this.manyList = res.data
      } else {
        this.onlyList = res.data
      }
    },
    handleTabClick() {
      console.log(this.activeName)
      console.log(this.manyList)
      this.getTabData()
    },
    // 显示添加模态框
    showAddDialog() {
      this.addDialogVisible = true
    },
    addFormClose() {
      this.$refs.addFormRef.resetFields()
    },
    editFormClose() {
      this.$refs.editFormRef.resetFields()
    },
    addFormPost() {
      this.$refs.addFormRef.validate(async validate => {
        // console.log(validate)
        if (!validate) return
        const { data: red } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (red.meta.status !== 201) {
          return this.$message.error('添加失败')
        }
        this.getTabData()
        this.addDialogVisible = false
      })
    },
    async showEditDialog(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/` + id)
      console.log(res)
      this.editForm = res.data
    },
    editFormPost() {
      this.$refs.editFormRef.validate(async validate => {
        // console.log(validate)
        if (!validate) return
        console.log(this.editForm.attr_id)

        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        })
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('修改参数失败')
        this.$message.success('修改参数成功')
        this.getTabData()
        this.editDialogVisible = false
      })
    },
    async deleteCate(id) {
      const result = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      //   console.log(result)
      if (result !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
      console.log(res)

      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      this.getTabData()
    },
     handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false
        row.inputValue = ''
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputVisible = false
      row.inputValue = ''
       this.saveChange(row)
    },
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async saveChange(row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('修改参数失败')
      this.$message.success('修改参数成功')
    },
    handleClose(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveChange(row)
    }
  },
  created() {
    this.getCateData()
  },
  computed: {
    btnLocked() {
      if (this.selectedKeys.length === 3) {
        return false
      } else {
        return true
      }
    },
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      } else {
        return null
      }
    },
    textTitle() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 10px;
}
.el-tag {
  margin: 0 5px;
}
.input-new-tag {
  width: 120px;
}
</style>
